﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Kise.LprCapturer
{
    class PacketBuilder
    {
        public byte[] BuildTimeSync(DateTime localTime)
        {
            var unixTime = (uint)ConvertLocalTimeToUnixTime(localTime);
            return BuildPacket(0xf2, (int)unixTime, 0);
        }

        private long ConvertLocalTimeToUnixTime(DateTime time)
        {
            var utcTime = time.Kind != DateTimeKind.Utc ? time.ToUniversalTime() : time;
            var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            var span = (utcTime - epoch).TotalSeconds;

            return Convert.ToInt64(span);
        }

        public byte[] BuildH264Command(int command)
        {
            const int cmdType = unchecked((int)0xffff000e);
            return BuildPacket(cmdType, command, 0);
        }

        private byte[] BuildPacket(int commandType, int arg1, int arg2)
        {
            using (var memStream = new MemoryStream())
            using (var writer = new StreamWriter(memStream))
            {
                writer.Write(commandType);
                writer.Write(arg1);
                writer.Write(arg2);
                return memStream.ToArray();
            }

        }
    }
}
